package com.gem.springbootdemo.util;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component //实例化对象
public class UrlInterceptor implements HandlerInterceptor {
//    请求control拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path=request.getRequestURI();
        if (path.endsWith("index")||path.endsWith("infor")||
            path.endsWith("toLogin")||path.endsWith("login")||
                path.endsWith("register")||path.endsWith("isUsernameExist")||path.endsWith("/")
        ){
            return true;
        }
        HttpSession session=request.getSession();
        Object user=session.getAttribute("user");
        if (user!=null){
            //代表登录
            return  true;
        }
        //跳转到登录页面
        request.getRequestDispatcher("/toLogin").forward(request,response);
        return false;
    }
}
